#include "thread.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

static void * threadfibo(void * arg)
{
  int n = (int)arg;
  int err;
  thread_t th1,th2;
  void *retval1,*retval2;
  
  if (n == 0)
    thread_exit((void *)0);
  else if (n == 1)
    thread_exit((void *)1);
  else{ 
    err = thread_create(&th1, threadfibo, (void *)(n-1));
    assert(!err);
    err = thread_create(&th2, threadfibo, (void *)(n-2));
    assert(!err);
    

    err = thread_join(th1, &retval1);
    assert(!err);
    err = thread_join(th2, &retval2);
    assert(!err);

    thread_exit((void *)((int)retval1+(int)retval2));
  }
}

int main(int argc, char *argv[])
{
  thread_t th;
  void *retval;
  int err;

  if (argc != 2){
    printf("Veuillez lancer avec 1 argument: numero de nombre fibonacci\n");
    return 1;
  }

  init();
  printf("creation de thread\n");
  err = thread_create(&th, threadfibo, (void *)(atoi(argv[1])));
  assert(!err);
  printf("lancement le thread de calcul %p\n", th);

  err = thread_join(th, &retval);
  assert(!err);
  printf("les threads ont termine et le resultat est %d\n", (int)retval);

  return 0;
}
